package cn.itsource.pet.service.impl;

import cn.itsource.base.service.impl.BaseServiceImpl;
import cn.itsource.base.util.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.service.IOrderPetAcquisitionService;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.domain.dto.AcceptDto;
import cn.itsource.pet.domain.dto.SearchDto;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private TextCensor textCensor;
    @Autowired
    private SearchMasterMsgAuditLogMapper msgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;


    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        super.save(searchMasterMsg);
        Date date = new Date();
        //使用百度AI审核
        // 没通过 直接返回数据告诉前端
//        if(textCensor.TextCensor(searchMasterMsg.getName())){
//            return getResult(searchMasterMsg, date,"宠物名不合规:" + searchMasterMsg.getName());
//        }
//        if(textCensor.TextCensor(searchMasterMsg.getTitle())){
//            return getResult(searchMasterMsg, date,"标题不合规:" + searchMasterMsg.getTitle());
//        }
//        if(textCensor.TextCensor(searchMasterMsg.getCoatColor())){
//            return getResult(searchMasterMsg, date,"毛色不合规:" + searchMasterMsg.getCoatColor());
//        }
//        if(textCensor.TextCensor(searchMasterMsg.getAddress())){
//            return getResult(searchMasterMsg, date,"地址不合规:" + searchMasterMsg.getAddress());
//        }
        // 通过  -- 记录审核日志
        recordAuditLog(searchMasterMsg.getId(), date,"审核通过",1);
        searchMasterMsg.setState(1);
        searchMasterMsg.setNote("审核通过");

        String address = searchMasterMsg.getAddress();//自己的地址
        Point myPoint = DistanceUtils.getPoint(address);
        List<Shop> shopList = shopMapper.selectAll();
        //门店的地址 查询所有的店铺--得到他的地址
        // 有可能会推送最近的店铺
        // 附近有店铺[1个店铺或多个店铺{多个店铺选其中最近的哪一个}] 附近没有店铺
        //最近一个怎么去确定  通过你的地址和店铺地址去计算 得出最近一个店铺
        // 将店铺id保存的 寻主信息里面
        //将用户的填写的信息保存到数据库-- 有  必须要审核通过才保存
        Shop nearestShop = DistanceUtils.getNearestShop(myPoint, shopList);
        //计算  看有没有在20公里之内
        if(nearestShop == null){
            update(searchMasterMsg);
        }else {
            searchMasterMsg.setShopId(nearestShop.getId());
            update(searchMasterMsg);
        }
        return AjaxResult.me();
    }

    @Override
    public AjaxResult getMyPublishPets(Long userId) {
        List<SearchMasterMsg> msg =  searchMasterMsgMapper.getMyPublishPets(userId);
        return AjaxResult.me().setResultObj(msg);
    }

    @Override
    public AjaxResult toSearchMasterPool(SearchMasterMsgQuery query) {
        if(query.getCurrentPage() < 1){
            throw new RuntimeException("");
        }
        //分页查询
        query.setState(SearchMasterMsgQuery.state_pool);
        List<SearchMasterMsg> poolMasterMsgs = searchMasterMsgMapper.query(query);
        //创建分页接收对象
        PageList<SearchMasterMsg> pageList = new PageList();
        //设置分页数据
        pageList.setData(poolMasterMsgs);
        //设置分页总条数
        pageList.setCount(searchMasterMsgMapper.queryCount(query));

        return AjaxResult.me().setResultObj(pageList);
    }

    @Override
    public AjaxResult toHandle(SearchMasterMsgQuery query,Long logininfoId) {
        if(query.getCurrentPage() < 1){
            throw new RuntimeException("");
        }
        //获取店铺id
        Shop shop = shopMapper.selectByLoginId(logininfoId);
        if(shop == null){
            return AjaxResult.me().setSuccess(false).setMessage("你没有店铺！");
        }
        //分页查询
        query.setShopId(shop.getId());
        List<SearchMasterMsg> poolMasterMsgs = searchMasterMsgMapper.query(query);
        //创建分页接收对象
        PageList<SearchMasterMsg> pageList = new PageList();
        //设置分页数据
        pageList.setData(poolMasterMsgs);
        //设置分页总条数
        pageList.setCount(searchMasterMsgMapper.queryCount(query));
        return AjaxResult.me().setResultObj(pageList);
    }

    @Override
    public AjaxResult reject(Long searchMsgId) {
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.selectById(searchMsgId);
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me();
    }

    @Override
    @Transactional
    public AjaxResult accept(AcceptDto acceptDto,Long logininfoId) {
        //查询店铺
        Shop shop = shopMapper.selectByLoginId(logininfoId);
        //查询寻主消息
        Long msgId = acceptDto.getMsgId();
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.selectById(msgId);
        //1 添加一个收购单
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setShopId(shop.getId());
        orderPetAcquisition.setOrderSn(StrUtils.getRandomString(16));
        orderPetAcquisition.setDigest(searchMasterMsg.getName() + "的收购订单");
        //最后确认时间是当前时间+2两天
        long lastcomfirmtimeLong = System.currentTimeMillis()+1000*60*60*24*2;
        orderPetAcquisition.setLastcomfirmtime(new Date(lastcomfirmtimeLong));
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(searchMasterMsg.getPrice());
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(acceptDto.getEmployeeId());
        orderPetAcquisition.setSearchMasterMsgId(msgId);
        orderPetAcquisitionService.save(orderPetAcquisition);
        //2 修改msg的状态
        searchMasterMsg.setState(2);
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me();
    }

    @Override
    public AjaxResult shopReceivePet(SearchDto dto, Long loginId) {
        //获取店铺id
        Shop shop = shopMapper.selectByLoginId(loginId);
        if(shop == null){
            return AjaxResult.me().setSuccess(false).setMessage("你没有店铺！");
        }
        //查询出当前选中的寻主信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.selectById(dto.getSearchId());
        searchMasterMsg.setShopId(shop.getId());
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me();
    }



    private AjaxResult getResult(SearchMasterMsg searchMasterMsg, Date date,String message) {
        recordAuditLog(searchMasterMsg.getId(), date,message,0);
        searchMasterMsg.setNote(message);
        searchMasterMsg.setState(-1);
        super.update(searchMasterMsg);
        return AjaxResult.me().setSuccess(false).setMessage(message);
    }

    private void recordAuditLog(Long msgId, Date date, String note, Integer state) {
        SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
        searchMasterMsgAuditLog.setAuditTime(date);
        searchMasterMsgAuditLog.setState(state);
        searchMasterMsgAuditLog.setNote(note);
        searchMasterMsgAuditLog.setMsgId(msgId);
        msgAuditLogMapper.save(searchMasterMsgAuditLog);
    }
}
